import requests
import bs4

def open_url(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    res = requests.get(url, headers=headers)
    return res

def main():
  name = input("请输入需要查询的关键字：")
  pageCount = int(input("请输入需要爬取的页数："))
  with open("Bilibili.txt", "w", encoding="utf8") as f:
      f.write("")
      f.close()
  for n in range(pageCount):
      res = open_url("https://search.bilibili.com/all?keyword=" + name + "&page=" + str(n + 1))
      soup = bs4.BeautifulSoup(res.text, "html.parser")
      titles = soup.find_all("li", class_="video-item matrix")
      for item in titles:
        with open("Bilibili.txt", "a", encoding="utf8") as f:
          f.write(str(titles.index(item) + 1) + "：" + item.a['title'] + "(https:" + item.a['href'] + ")" + "\n\n")
          f.close()

if __name__ == "__main__":
    main()
